package org.example.servlet;

import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/AdminRegisterServlet")
public class AdminRegisterServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(AdminRegisterServlet.class);
    private static final String ADMIN_KEY = "123456"; // 固定密钥

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("adminUsername");
        String password = request.getParameter("adminPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        String email = request.getParameter("email");
        String securityCode = request.getParameter("securityCode");

        // 验证密钥
        if (!ADMIN_KEY.equals(securityCode)) {
            request.setAttribute("error", "管理员密钥不正确");
            request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
            return;
        }

        // 验证密码是否匹配
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            // 获取数据库连接
            conn = DataSourceUtil.getDataSource().getConnection();

            // 检查用户名是否已存在
            if (isUsernameExists(conn, username)) {
                request.setAttribute("error", "用户名已存在");
                request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
                return;
            }

            // 检查邮箱是否已存在
            if (isEmailExists(conn, email)) {
                request.setAttribute("error", "邮箱已存在");
                request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
                return;
            }

            // 创建管理员账户
            String sql = "INSERT INTO admins (username, password, email) VALUES (?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.setString(3, email);

            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                // 注册成功，重定向到登录页面
                response.sendRedirect("Adminlogin.jsp");
                return;
            } else {
                request.setAttribute("error", "创建管理员账户失败");
                request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
            }

        } catch (SQLException e) {
            logger.error("创建管理员数据库错误: {}", e.getMessage());
            request.setAttribute("error", "数据库错误，请稍后再试");
            request.getRequestDispatcher("Adminregister.jsp").forward(request, response);
        } finally {
            // 关闭资源
            closeResources(null, stmt, conn);
        }
    }

    private boolean isUsernameExists(Connection conn, String username) throws SQLException {
        String sql = "SELECT id FROM admins WHERE username = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, username);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next();
            }
        }
    }

    private boolean isEmailExists(Connection conn, String email) throws SQLException {
        String sql = "SELECT id FROM admins WHERE email = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, email);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next();
            }
        }
    }

    private void closeResources(ResultSet rs, PreparedStatement stmt, Connection conn) {
        try { if (rs != null) rs.close(); } catch (SQLException e) { logger.error("关闭ResultSet错误: {}", e.getMessage()); }
        try { if (stmt != null) stmt.close(); } catch (SQLException e) { logger.error("关闭PreparedStatement错误: {}", e.getMessage()); }
        try { if (conn != null) conn.close(); } catch (SQLException e) { logger.error("关闭Connection错误: {}", e.getMessage()); }
    }
}